<template>
  <TopNav :title="metaTitle" />
  <Listing
    v-if="items && items.results.length"
    :title="metaTitle"
    :items="items"
    :loading="loading"
    @loadMore="loadMore"
  />
</template>

<script setup>
import { getListItem, getTrending, getMovies } from "@/api";
import TopNav from "@/components/TopNav.vue";
import Listing from "@/components/Listing.vue";
import { ref, computed } from "vue";
import { useRoute } from "vue-router";

const loading = ref(false);
const items = ref(null);

const route = useRoute();

const metaTitle = computed(() => {
  return getListItem("movie", route.params.name).title;
});


const isTrending = computed(() => {
  return route.params.name === "trending"; 
})

if(isTrending.value ){
    getTrending('movie').then((res)=>{
        items.value = res; 
    })
}else{
    getMovies(route.params.name).then((res)=>{
        items.value = res;
    })
}


const loadMore = () => {
  loading.value = true;

  let request = getMovies(route.params.name, items.value.page + 1);
  if (isTrending.value) {
    request = getTrending("movie", items.value.page + 1);
  }

  request
    .then((res) => {
      items.value.results = items.value.results.concat(res.results);
      items.value.page = res.page;
    })
    .finally(() => {
      loading.value = false;
    });
};
</script>
